<template>
  <div>
    <!-- 导航栏区域 -->
    <!-- 布尔类型的属性，写上就是true -->
    <van-nav-bar fixed placeholder title="购物车案例" />

    <!-- 商品列表 -->
    <van-cell-group style="margin-bottom: 50px;">
      <van-cell v-for="item in list" :key="item.goods_id">
        <!-- 里面写自定义的内容 -->
        <div style="display:flex;">
          <!-- 左侧图片和多选 -->
          <van-checkbox v-model="item.goods_state" shape="square">
            <van-image
              width="120"
              height="120"
              radius="10"
              fit="cover"
              :src="item.goods_img"
            />
          </van-checkbox>
          <!-- 右侧标题、价格、数量 -->
          <div style="margin-left:10px;flex: 1;">
            <h3>{{ item.goods_name }}</h3>
            <div>
              <span style="color:red;">￥ {{ item.goods_price }}</span>
              <van-stepper v-model="item.goods_count" style="float:right;" />
            </div>
          </div>
        </div>
      </van-cell>
    </van-cell-group>

    <!-- 订单栏区域 -->
    <van-submit-bar :price="totalPrice" :button-text="totalCount">
      <van-checkbox v-model="checkAll">全选</van-checkbox>
    </van-submit-bar>
  </div>
</template>

<script>
// 导入axios
import axios from 'axios'
export default {
  data () {
    return {
      list: []
    }
  },
  async created () {
    const res = await axios({
      url: 'https://applet-base-api-t.itheima.net/api/cart'
    })
    this.list = res.data.list
  },
  computed: {
    totalPrice () {
      return this.list.reduce( (sum, v) => {

        if (v.goods_state) {
          sum += v.goods_price * v.goods_count
        }
        return sum
      }, 0) * 100
    },
    totalCount () {
       const num =  this.list.reduce( (sum, v) => {

        if (v.goods_state) {
          sum += v.goods_count
        }
        return sum
      }, 0)
      return `结算(${num}件)`
    },

    checkAll: {
      get () {
        return this.list.every(v => v.goods_state)
      },

      set (val) {
        this.list.forEach(v => v.goods_state = val)
      }
    }
  }
}
</script>

<style></style>
